/*
 * @Author: your name
 * @Date: 2024-03-27 12:58:07
 * @LastEditTime: 2024-03-27 16:58:59
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\54.螺旋矩阵.cpp
 */
/*
 * @lc app=leetcode.cn id=54 lang=cpp
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> ans;
        int x1 = 0,y1 = 0, x2 = n-1, y2 = m-1;
        int i = 0, j = 0;
        while(1){
            if(x1==x2 && y1==y2){
                ans.push_back(matrix[x1][y1]);
                break;
            }
            else if(x1>x2 || y1>y2){
                break;
            }
            for(i = x1; i < x2; i++){
                ans.push_back(matrix[y1][i]);
            }
            for(j = y1; j < y2; j++){
                ans.push_back(matrix[j][x2]);
            }
            for(i = x2; i > x1; i--){
                ans.push_back(matrix[y2][i]);
                /// 解决只有一行时，会多pushback的问题
                if(y1==y2){
                    break;
                }
            }
            for(j = y2; j > y1; j--){
                ans.push_back(matrix[j][x1]);
                if(x1==x2){
                    break;
                }
            }
            x1++;
            y1++;
            x2--;
            y2--;
            

        }
        return ans;
    }
};
// @lc code=end

